import { Select } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref, type PropType } from 'vue'
import type { JsonSchema } from '../types'
import type { SelectProps } from 'ant-design-vue'
import { getProp } from '@/components/cms/utils'
import { formState } from '../mixins/useState'

export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    }
  },
  setup(props, ctx) {
    const selected = ref<string | number | undefined>(undefined)
    const attrs = { ...props.schema.props } as SelectProps

    const handleChange = () => {
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      }
      const value = {
        path: props.schema.field,
        value: Number(selected.value)
      }
      ctx.emit('valueChange', value)
    }

    onMounted(() => {
      nextTick(() => {
        const value = getProp(formState.model, props.schema.field as string).value as string
        selected.value = value
      })
    })
    return () => <Select {...attrs} v-model={[selected.value, 'value']} onChange={() => handleChange()} />
  }
})
